<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->
<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="bg-white rounded-lg shadow p-6 min-h-[calc(100vh-3rem)]">
      <!-- 顶部操作区 -->
      <div class="flex justify-between items-center mb-6">
        <el-button type="primary" class="!rounded-button" @click="handleAdd">
          <el-icon class="mr-1">
            <Plus />
          </el-icon>
          新增标签
        </el-button>

        <div class="flex items-center">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入标签名称"
            class="w-64 mr-2"
            clearable
          >
            <template #prefix>
              <el-icon>
                <search />
              </el-icon>
            </template>
          </el-input>
          <el-button
            type="primary"
            class="!rounded-button"
            @click="handleSearch"
          >
            搜索
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        stripe
        border
        class="w-full"
        v-loading="loading"
      >
        <!--        <el-table-column prop="id" label="ID" width="80" />-->

        <el-table-column prop="tagName" label="标签名称" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateUser" label="更新人" width="120" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column prop="isDelete" label="是否删除" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isDelete ? 'danger' : 'success'">
              {{ row.isDelete ? "已删除" : "正常" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              class="!rounded-button"
              @click="handleEdit(row)"
              :disabled="row.isDelete"
            >
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button
              type="danger"
              class="!rounded-button ml-2"
              @click="handleDelete(row)"
              :disabled="row.isDelete"
            >
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- 分页 -->
      <div style="display: flex" class="block">
        <el-pagination
          class="block"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="10"
          :total="tableData.length"
          layout="pager"
        />
      </div>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogType === 'add' ? '新增标签' : '编辑标签'"
        v-model="dialogVisible"
        width="500px"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="标签名称" prop="tagName">
            <el-input v-model="formData.tagName" placeholder="请输入标签名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button class="!rounded-button" @click="dialogVisible = false"
              >取消</el-button
            >
            <el-button
              class="!rounded-button"
              type="primary"
              @click="handleSubmit"
            >
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search, Edit, Delete } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { TagsControllerService } from "../../../backendapi";
interface TagItem {
  id: number;
  createTime: string;
  tagName: string;
  updateUser: string;
  updateTime: string;
  isDelete: boolean;
}

const loading = ref(false);
const searchKeyword = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const formRef = ref<FormInstance>();

const formData = reactive({
  id: 0,
  tagName: "",
});

const rules = {
  tagName: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
};

const tableData = ref<TagItem[]>([]);

const fetchData = async () => {
  loading.value = true;
  try {
    const response = await TagsControllerService.findPageUsingGet1(
      currentPage.value,
      pageSize.value,
      searchKeyword.value
    );
    tableData.value =
      response.data?.records.map((tag) => ({
        ...tag,
        isDelete: tag.isDelete === 1,
      })) || [];
    total.value = response.data?.total || 0;
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = async () => {
  currentPage.value = 1;
  await fetchData();
};
const handleSizeChange = async (val: number) => {
  pageSize.value = val;
  await handleSearch();
};
const handleCurrentChange = async (val: number) => {
  currentPage.value = val;
  await handleSearch();
};
const handleAdd = () => {
  dialogType.value = "add";
  formData.id = 0;
  formData.tagName = "";
  dialogVisible.value = true;
};

const handleEdit = async (row: TagItem) => {
  dialogType.value = "edit";
  try {
    const response = await TagsControllerService.findOneUsingGet1(row.id);
    formData.id = response.data.id;
    formData.tagName = response.data.tagName;
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error("获取标签信息失败");
  }
};

const handleDelete = (row: TagItem) => {
  ElMessageBox.confirm("确认要删除该标签吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await TagsControllerService.deleteUsingDelete1(row.id);
      ElMessage.success("删除成功");
      await fetchData();
    } catch (error) {
      ElMessage.error("删除失败");
    }
  });
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await TagsControllerService.saveUsingPost1({
            tagName: formData.tagName,
          });
          ElMessage.success("添加成功");
        } else {
          await TagsControllerService.updateUsingPut1({
            id: formData.id,
            tagName: formData.tagName,
          });
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        await fetchData();
      } catch (error) {
        ElMessage.error(dialogType.value === "add" ? "添加失败" : "修改失败");
      }
    }
  });
};

// 初始化数据
fetchData();
</script>

<style scoped>
.el-input {
  --el-input-inner-height: 40px;
}

.el-button {
  height: 40px;
}
</style>
